import React, { useEffect ,useRef,useState} from "react";
import * as d3 from 'd3'
import useSyncState from "./graph";

// import * as ccd3 from 'ccd3'


import axios from 'axios'
import { Button } from 'antd'
import { fcumsum } from "d3";
function GraphSource() {

    console.log("!!!!!!!!!!!!!")
    
    const[data1,setData1]=useState([])


    const[data2,setData2]=useState([])
    const[data ,setData]=useSyncState([])
   
    const svgRef = useRef()
    // const dataRef = useRef(data1)

  

   

useEffect(()=>{
 getData()
},[])

const getData=()=>{
    axios.get(`http://8.135.113.164:8000/knowledgegraph/transformer?name=%E4%B8%AD%E5%9B%BD&labels=%E5%9B%BD%E5%AE%B6`, {
        // params:{
        //     name: '中国',
        //     labels:'国家'
        // }
    }).then(res => {
        let array = []
        let array1 = []
        let result  = []

        for(var i in res.data[0]){
            array.push(res.data[0][i])
        }
        for(var i in res.data[1]){
            array1.push(res.data[1][i])
        }
        result.nodes = array
        result.links = array1
        console.log('arrayall',result)
        fn(result)
    })
};

useEffect(()=>{
    console.log(data1);
    if(data1){
        fn(data1)
    }
    
},[data1])

    // console.time("结束时间")
  
const fn =(result)=>{
    if(result!=null){
        console.log('_______',result)
        
        const nodess =  result.nodes.map((d) => Object.create(d));
        const linkss =  result.links.map((d) => Object.create(d));
        const color = (d) => {
            switch(d.__proto__.size){
                case 1:return '#bab0ac';break;
                case 2:return '#ff9da7';break;
                case 3:return'#76b7b2';break;
                case 4:return'#b07aa1';break;
                case 5:return'#e15759';break;
                case 6:return'#667d96';break; 
                case 7:return'#edc948';break;
                case 8:return'#BFD8B8';break;
                case 9:return'#59a14f';break;
                case 10:return'#4e79a7';break;
              
            }
            };
       
            const draggraph = (simulation) => {
                function dragstarted(event) {
                    if (!event.active) simulation.alphaTarget(0.3).restart();
                    event.subject.fx = event.subject.x;
                    event.subject.fy = event.subject.y;
                }
                function dragged(event) {
                    event.subject.fx = event.x;
                    event.subject.fy = event.y;
                }
                function dragended(event) {
                    if (!event.active) simulation.alphaTarget(0);
                    event.subject.fx = null;
                    event.subject.fy = null;
                }
                return d3.drag()
                    .on('start', dragstarted)
                    .on('drag', dragged)
                    .on('end', dragended);
            };
        
            const width =d3.select('#GraphSource')._groups[0][0].offsetWidth ;
            const height =d3.select('#GraphSource')._groups[0][0].offsetHeight ;
            const margin = { top: 20, right: 30, bottom: 20, left: 30 };
            
          
            // const nodess = data1.map((d) => Object.create(d));
            // const linkss = data1.map((d) => Object.create(d));
            const chartid = "chart-places";
            // console.log(nodess.length)
            // console.log(linkss)
            const simulation = d3.forceSimulation(nodess)
                .force(
                    'link',
                    d3.forceLink(linkss).id((d) => d.name).distance(150)
                )
                .force('collision', d3.forceCollide().radius(1).strength(1))
                .force('charge', d3.forceManyBody())
                .force('center', d3.forceCenter(width / 2, height / 2));
        
            const svg = d3.select(svgRef.current)    
                // .append('svg')
                .attr('width', width)
                .attr('height', height)
                .attr("id",chartid)
                .on("click", reset)
              
            const link = svg
                .append('g')
                .attr('stroke', '#999')
                .attr('stroke-opacity', 0.5)
                .selectAll('line')
                .data(linkss)
                .join('line')
                .attr('cursor','pointer')
                .attr('stroke-width', (d) => Math.sqrt(d.value))
                .attr('transform', `translate(${margin.left},${margin.top})`)
        
            //存储相连节点--相连节点高亮
            const nodeLinkStatus = {};
            linkss.forEach(d => {
                //   console.log(d)
                  nodeLinkStatus[`${d.source.index},${d.target.index}`] = 1;
                });
            // console.log(nodeLinkStatus)
             
            function isConnected(a, b) {
                 return nodeLinkStatus[`${a.index},${b.index}`] || nodeLinkStatus[`${b.index},${a.index}`] || a.index === b.index;
               }
            function isConnected2(a,n) {
                return nodeLinkStatus[`${a.index},${n}`] || nodeLinkStatus[`${n},${a.index}`] 
            }
                
            const node = svg
                .append('g')
                .attr('class',"team-nodes")
                .attr('stroke', '#fff')
                .attr('stroke-width', 1.5)
                .selectAll('circle')
                .data(nodess)
                .join('circle')
                .attr('r', d => d.size*3)
                .attr('fill', color)
                .attr('fill-opacity', 1)
                 .attr('cursor','pointer')
                .attr('transform', `translate(${margin.left},${margin.top})`)
                .call(draggraph(simulation))   
                .on('mouseover', (d, i) => {
                    // console.log(i)
                    console.log("d",i)    
                    let conn=0
                    link.style("stroke", function (d) {
                        // console.log(d)
                        if (i.__proto__.name === d.source.__proto__.name || i.__proto__.name == d.target.__proto__.name) {
                            conn++
                            return "#142334"
                        }
      
                    })
                    link.style('stroke-opacity', d => {
                        if (i.__proto__.name === d.source.__proto__.name || i.__proto__.name == d.target.__proto__.name) {
                            return 0.8
                        }
                        else {
                            return 0.1
                        }
                    })
                    node.attr("r",d=>{
                 
                      if(i.index === d.index ){
                         return d.size*4
                      }
                      else{
                          return d.size*3
                      }
                  })
                  node.attr('stroke-opacity', function (o) {
                    var thisOpacity = 0;
                    if(isConnected(i, o)){
                      thisOpacity = 1;
                    } else{
                      thisOpacity = 0.1;
                    }
                    this.setAttribute('fill-opacity', thisOpacity);
                    return thisOpacity; 
                  })
    
                  textElements.attr('fill-opacity',d=>{
                      var thisOpacity = 0;
                      if(isConnected(i, d)){
                        thisOpacity = 0.8;
                      } else{
                        thisOpacity = 0.5;
                      }
                      return thisOpacity;
                  })
    
                    tooltip.html("name:" + i.__proto__.name + "<br />" + "size:" + i.__proto__.size + "<br />"+"connection:"+conn )
                    // .transition()
                    // .duration(100)
                    .style("left", (d.pageX) + "px")
                    .style("top", (d.pageY+5) + "px")
                    .style("opacity", 0.8)
                    .style("visibility", "visible");
                })
                .on('mouseout', (d, i) => {
                    link.style("stroke", '#999')
                    link.style("stroke-opacity", 0.5)
                    tooltip.style("visibility", "hidden")
               
                    node.attr("r", d=>d.size*3)
                    node.attr("fill-opacity",1)
                    textElements.attr("fill-opacity",0.5)
                })


                .on('dblclick',(d,i)=>dbclick(d,i))
                .on("click",clicked)
    
            //点击节点，将节点zoom到屏幕中间
            function dbclick(d,i){
                console.log("d and i",d)
                let data_back1 =[]
                let data_back2 =[]
                
                let result2 =[]
                // console.log(i.__proto__)
                axios.get(`http://8.135.113.164:8000/knowledgegraph/findsource?name=%E7%8E%89%E7%99%BB%E7%BA%A7%E4%B8%AD%E5%9E%8B%E7%99%BB%E9%99%86%E8%88%B0&labels=%E5%90%8D%E7%A7%B0`, {
                    params:{
                        // name: i.__proto__.name,
                        // label: i.__proto__.label,
                    }
                }).then(res => {
                    if(data_back1 == undefined) {
                        data_back1 = []
                      }
                    console.log('result',result)
                    console.log("ressssss",res)
            
                    for(var i in res.data[0]){
                        data_back1.push(res.data[0][i])
                        }
                        for(var i in res.data[1]){
                            data_back2.push(res.data[1][i])
                        }
                        result2.nodes = data_back1
                        result2.links = data_back2
                      d3.select("#tooltip").remove()
                      d3.selectAll('svg').remove()
                      d3.selectAll('tooltip').remove()   
                    // 画的数据
                      setData1(result2)
                })
            }
            function clicked(event,d){
                const [[x0,y0],[x1,y1]] = [[d.x-100,d.y-100],[d.x+100,d.y+100]]
                event.stopPropagation()
                svg.transition().duration(750).call(
                    zoomm.transform,d3.zoomIdentity.translate(width / 2, height / 2)
                    .scale(Math.min(8, 0.9 / Math.max((x1 - x0) / width, (y1 - y0) / height)))
                    .translate(-(x0 + x1) / 2, -(y0 + y1) / 2),d3.pointer(event,svg.node())
                )
            }
            // click背景返回
            function reset() {
                svg.transition().duration(750).call(
                  zoomm.transform,
                  d3.zoomIdentity,
                  d3.zoomTransform(svg.node()).invert([width / 2, height / 2])
                );
              }
                    
            const textElements = svg.append('g')
                .selectAll('circle')
                .data(nodess)
                .enter().append('text')
                .text(d=> {
                        var name = null;
                        if(isConnected2(d, 1034)){
                            name = null;
                        } else{
                          name = d.name;
                        }
                        return name;
                    }
                    // console.log(node)  
                )
                .attr('font-size', d=>{
                    if (d.size>8){
                        return d.size+4
                    }
                    else{
                        return 6
                    }
                })
                .attr('dx', (d,i,event)=>{
                    return 10
                })
                .attr('dy', 4)
                .attr("font-weight",'bold')
                .attr("fill-opacity",(d,i)=>{
              
    
                    return 0.5
                })

            const tooltip = d3.select("body")
                .append("div")
                .attr("id", "tooltip")
                .style("visibility", "hidden")
                .style("position",'absolute')
                .style("font-size",'15px')
                .style("padding", "10px")
                .style("z-index", "10")
                .style("font-weight",'bold')
                .style("height","auto")
                .style("background-color", "rgba(230, 242, 255, 0.8)")
                .style("width","auto")
                .style("border-radius", "5px")

            const zoomm = d3
                .zoom()
                .extent([
                    [0, 0],
                    [width, height],
                ])
                .scaleExtent([0.1, 8])
                .on('zoom', zoomed)
    
            svg.call(zoomm).on("dblclick.zoom", null);
            
            function zoomed({ transform }) {
                link.attr('transform', transform);
                node.attr('transform', transform);
                textElements.attr('transform', transform);
              
            }
            
            simulation.on('tick', () => {
                link
                    .attr('x1', (d) => d.source.x)
                    .attr('y1', (d) => d.source.y)
                    .attr('x2', (d) => d.target.x)
                    .attr('y2', (d) => d.target.y);
                textElements
                    .attr("x", node => node.x)
                    .attr("y", node => node.y);
                node.attr('cx', (d) => d.x).attr('cy', (d) => d.y);
                if(simulation.alpha<=0.065){
                    simulation.stop()
                }
            });
    }
}



    
return (
        <div id="GraphSource"
            style={{
                margin: "1rem ",
                backgroundColor: "#fff",
                height: "80vh",
                width: "75vw"
            }}
        > 
          <svg ref={svgRef}></svg>
        
        </div>
    )
}
export { GraphSource }